<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java,HTTP,Netty," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言两天前写了文章《「造个轮子」——cicada(轻量级 WEB 框架)》
 向大家介绍了 cicada 之后收到很多反馈，也有许多不错的建议。
同时在 GitHub 也收获了 100 多颗 小♥♥（绝对不是刷的。。）

也有朋友希望能出一个源码介绍，本文就目前的 v1.0.1 版本来一起分析分析。

没有看错，刚发布就修复了一个 bug，想要试用的请升级到 1.0.1 吧。">
<meta property="og:type" content="article">
<meta property="og:title" content="「造个轮子」——cicada 源码分析">
<meta property="og:url" content="http://crossoverjie.top/2018/09/05/wheel/cicada2/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言两天前写了文章《「造个轮子」——cicada(轻量级 WEB 框架)》
 向大家介绍了 cicada 之后收到很多反馈，也有许多不错的建议。
同时在 GitHub 也收获了 100 多颗 小♥♥（绝对不是刷的。。）

也有朋友希望能出一个源码介绍，本文就目前的 v1.0.1 版本来一起分析分析。

没有看错，刚发布就修复了一个 bug，想要试用的请升级到 1.0.1 吧。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d14f1f2b1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15189c70.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15386288.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15aa7f17.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15ca2e73.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15e4425b.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d15f63262.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d160649b6.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d16783d38.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d168565eb.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1694b1c1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d16a97d32.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d17122767.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d17301847.jpg">
<meta property="og:updated_time" content="2019-05-07T18:42:43.125Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="「造个轮子」——cicada 源码分析">
<meta name="twitter:description" content="前言两天前写了文章《「造个轮子」——cicada(轻量级 WEB 框架)》
 向大家介绍了 cicada 之后收到很多反馈，也有许多不错的建议。
同时在 GitHub 也收获了 100 多颗 小♥♥（绝对不是刷的。。）

也有朋友希望能出一个源码介绍，本文就目前的 v1.0.1 版本来一起分析分析。

没有看错，刚发布就修复了一个 bug，想要试用的请升级到 1.0.1 吧。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1d14f1f2b1.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/09/05/wheel/cicada2/"/>

  <title> 「造个轮子」——cicada 源码分析 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                「造个轮子」——cicada 源码分析
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-09-05T01:09:36+08:00" content="2018-09-05">
              2018-09-05
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/cicada/" itemprop="url" rel="index">
                    <span itemprop="name">cicada</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/cicada/轮子/" itemprop="url" rel="index">
                    <span itemprop="name">轮子</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/09/05/wheel/cicada2/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/09/05/wheel/cicada2/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/09/05/wheel/cicada2/" class="leancloud_visitors" data-flag-title="「造个轮子」——cicada 源码分析">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1d14f1f2b1.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>两天前写了文章<a href="https://crossoverjie.top/2018/09/03/wheel/cicada1/">《「造个轮子」——cicada(轻量级 WEB 框架)》
</a> 向大家介绍了 <code>cicada</code> 之后收到很多反馈，也有许多不错的建议。</p>
<p>同时在 GitHub 也收获了 100 多颗 小♥♥（绝对不是刷的。。）</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15189c70.jpg" alt=""></p>
<p>也有朋友希望能出一个源码介绍，本文就目前的 <code>v1.0.1</code> 版本来一起分析分析。</p>
<blockquote>
<p>没有看错，刚发布就修复了一个 bug，想要试用的请升级到 <code>1.0.1</code> 吧。</p>
</blockquote>
<a id="more"></a>
<h1 id="技术选型"><a href="#技术选型" class="headerlink" title="技术选型"></a>技术选型</h1><p>一般在做一个新玩意之前都会有技术选型的过程，但这点在做 <code>cicada</code> 的时候却异常简单。</p>
<p>因为我的需求是想提供一个高性能的 HTTP 服务，纵观整个开源界其实选择不多。</p>
<p>加上最近我在做 Netty 相关的开发，所以自然而然就选择了它。</p>
<p>同时 Netty 自带了对 HTTP 协议的编解码器，可以非常简单快速的开发一个 HTTP 服务器。我只需要把精力放在参数处理、路由等业务处理上即可。</p>
<p>同时 Netty 也是基于 NIO 实现，性能上也有保证。关于 Netty 相关内容可以参考<a href="https://crossoverjie.top/categories/Netty/">这里</a>。</p>
<p>下面来重点分析其中的各个过程。</p>
<h1 id="路由规则"><a href="#路由规则" class="headerlink" title="路由规则"></a>路由规则</h1><p>最核心的自然就是 HTTP 的处理 <code>handle</code>，对应的就是 <code>HttpHandle</code> 类。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15386288.jpg" alt=""></p>
<p>查看源码其实很容易看出具体的步骤，注释也很明显。</p>
<p>这里只分析重点功能。</p>
<p>先来考虑下需求。</p>
<p>首先作为一个 HTTP 框架，自然是得让使用者能有地方来实现业务代码；就像咱们现在使用 SpringMVC 时写的 <code>controller</code> 一样。</p>
<p>其实当时考虑过三种方案：</p>
<ul>
<li>像 SpringMVC 一样定义注解，只要声明了对应注解我就认为这是一个业务类。</li>
<li>用过 Struts2 的同学应该有印象，它的业务类 Action 都是配置到一个 XML 中；在里面配置接口对应的业务处理类。</li>
<li>同样的思路，只是把 XML 文件换成 <code>properties</code> 配置文件，在里面编写 JSON 格式的对应关系。</li>
</ul>
<p>这时就得分析各个方案的优缺点了。</p>
<p>方案二和三其实就是 XML 和 json 的对比了；XML 会让维护者感到结构清晰，同时便于维护和新增。</p>
<p>JSON 就不太方便处理了，并且在这样的场景并不用于传输自然也发挥不出优势。</p>
<p>最后考虑到现在流行的 SpringBoot 都在去 XML，要是再搞一个依赖于 XML 的东西也跟不上大家的使用习惯。</p>
<p>于是就采用类似于 SpringMVC 这样的注解形式。</p>
<p>既然采用了注解，那框架怎么知道用户访问某个接口时能对应到业务类呢？</p>
<p>所以首先第一步自然是需要将加有注解的类全部扫描一遍，放到一个本地缓存中。</p>
<p>这样才能方便后续的路由定位。</p>
<h1 id="路由策略"><a href="#路由策略" class="headerlink" title="路由策略"></a>路由策略</h1><p>其中核心的源码在 <code>routeAction</code> 方法中。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15aa7f17.jpg" alt=""></p>
<p>首先会全局扫描使用了 <code>@CicadaAction</code> 的注解，然后再根据请求地址找到对应的业务类。</p>
<p>全局扫描代码：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15ca2e73.jpg" alt=""></p>
<p>首先是获取到项目中自定义的所有类，然后判断是否加有 <code>@CicadaAction</code> 注解。</p>
<p>是目标类则把他缓存到一个本地 Map 中，方便下次访问时可以不再扫描直接从缓存中获取即可（反射很耗性能）。</p>
<p>执行完 <code>routeAction</code> 后会获得真正的业务类类型。</p>
<p><code>Class&lt;?&gt; actionClazz = routeAction(queryStringDecoder, appConfig);</code></p>
<h1 id="传参方式"><a href="#传参方式" class="headerlink" title="传参方式"></a>传参方式</h1><p>拿到业务类的类类型之后就成功一大半了，只需要反射生成它的对象然后执行方法即可。</p>
<p>在执行方法之前又要涉及到一个问题，参数我该怎么传递呢？</p>
<p>考虑到灵活性我采用了最简答 Map 方式。</p>
<p>因此定义了一个通用的 Param 接口并继承了 Map 接口。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Param</span> <span class="keyword">extends</span> <span class="title">Map</span>&lt;<span class="title">String</span>, <span class="title">Object</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get String</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">String <span class="title">getString</span><span class="params">(String param)</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get Integer</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">Integer <span class="title">getInteger</span><span class="params">(String param)</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get Long</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">Long <span class="title">getLong</span><span class="params">(String param)</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get Double</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">Double <span class="title">getDouble</span><span class="params">(String param)</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get Float</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">Float <span class="title">getFloat</span><span class="params">(String param)</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * get Boolean</div><div class="line">     * <span class="doctag">@param</span> param</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">Boolean <span class="title">getBoolean</span><span class="params">(String param)</span> </span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其中封装了几种基本类型的获取方式。</p>
<p>同时在 <code>buildParamMap()</code> 方法中，将接口中的参数封装到这个 Map 中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Param paramMap = buildParamMap(queryStringDecoder);</div></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15e4425b.jpg" alt=""></p>
<h1 id="业务执行"><a href="#业务执行" class="headerlink" title="业务执行"></a>业务执行</h1><p>最后只需要执行业务即可；由于在上文已经获取到业务类的类类型，所以这里通过反射即可调用。</p>
<p>同时也定义了一个业务类需要实现的一个通用接口 <code>WorkAction</code>，想要实现具体业务只要实现它就行。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d15f63262.jpg" alt=""></p>
<p>而这里的方法参数自然就是刚才定义的参数接口 <code>Param</code>。</p>
<p>由于所有的业务类都是实现了 <code>WorkAction</code>，所以在反射时都可以定义为 <code>WorkAction</code> 对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">WorkAction action = (WorkAction) actionClazz.newInstance();</div><div class="line">WorkRes execute = action.execute(paramMap);</div></pre></td></tr></table></figure>
<p>最后将构建好的参数 map 传入即可。</p>
<h1 id="响应返回"><a href="#响应返回" class="headerlink" title="响应返回"></a>响应返回</h1><p>有了请求那自然也得有响应，观察刚才定义的 <code>WorkAction</code> 接口可以发现其实定义了一个 <code>WorkRes</code> 响应类。</p>
<p>所有的响应数据都需要封装到这个对象中。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d160649b6.jpg" alt=""></p>
<p>这个没啥好说的，都是一些基本数据。</p>
<p>最后在 <code>responseMsg()</code> 方法中将响应数据编码为 JSON 输出即可。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d16783d38.jpg" alt=""></p>
<h1 id="拦截器设计"><a href="#拦截器设计" class="headerlink" title="拦截器设计"></a>拦截器设计</h1><p>拦截器也是一个框架基本的功能，用处非常多。</p>
<p><code>cicada</code> 的实现原理非常简单，就是在 <code>WorkAction</code> 接口执行业务逻辑之前调用一个方法、执行完毕之后调用另一个方法。</p>
<p>也是同样的思路需要定义一个接口 <code>CicadaInterceptor</code>，其中有两个方法。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d168565eb.jpg" alt=""></p>
<p>看方法名字自然也能看出具体作用。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1694b1c1.jpg" alt=""></p>
<p>同时在这两个方法中执行具体的调用。</p>
<p>这里重点要看看 <code>interceptorBefore</code> 方法。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d16a97d32.jpg" alt=""></p>
<p>其中也是加入了一个缓存，尽量的减少反射操作。</p>
<h2 id="适配器"><a href="#适配器" class="headerlink" title="适配器"></a>适配器</h2><p>就这样的拦截器接口是够用了，但并不是所有的业务都需要实现两个接口。</p>
<p>因此也提供了一个适配器 <code>AbstractCicadaInterceptorAdapter</code>。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d17122767.jpg" alt=""></p>
<p>它作为一个抽象类实现了 <code>CicadaInterceptor</code> 接口，这样后续的拦截业务也可继承该接口选择性的实现方法即可。</p>
<p>类似于这样：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d17301847.jpg" alt=""></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p><code>v1.0.1</code> 版本的 <code>cicada</code> 就介绍完毕了，其中的原理和源码都比较简单。</p>
<p>大量使用了反射和一些设计模式、多态等应用，这方面经验较少的朋友可以参考下。</p>
<p>同时也有很多不足；比如传参后续会考虑更加优雅的方式、拦截器目前写的比较死，后续会利用动态代理实现自定义拦截。</p>
<p>其实 <code>cicada</code> 只是利用周末两天时间做的，bug 肯定少不了；也欢迎大家在 GitHub 上提 <a href="https://github.com/TogetherOS/cicada/issues" target="_blank" rel="external">issue</a> 参与。</p>
<p>最后贴下项目地址：</p>
<p><a href="https://github.com/TogetherOS/cicada" target="_blank" rel="external">https://github.com/TogetherOS/cicada</a></p>
<p><strong>你的点赞与转发是最大的支持。</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
            <a href="/tags/HTTP/" rel="tag">#HTTP</a>
          
            <a href="/tags/Netty/" rel="tag">#Netty</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/03/wheel/cicada1/" rel="next" title="「造个轮子」——cicada(轻量级 WEB 框架)">
                <i class="fa fa-chevron-left"></i> 「造个轮子」——cicada(轻量级 WEB 框架)
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/07/translation/how-to-use-git-efficiently/" rel="prev" title="【译】如何高效的使用 Git">
                【译】如何高效的使用 Git <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#技术选型"><span class="nav-number">2.</span> <span class="nav-text">技术选型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由规则"><span class="nav-number">3.</span> <span class="nav-text">路由规则</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由策略"><span class="nav-number">4.</span> <span class="nav-text">路由策略</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#传参方式"><span class="nav-number">5.</span> <span class="nav-text">传参方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#业务执行"><span class="nav-number">6.</span> <span class="nav-text">业务执行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#响应返回"><span class="nav-number">7.</span> <span class="nav-text">响应返回</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#拦截器设计"><span class="nav-number">8.</span> <span class="nav-text">拦截器设计</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#适配器"><span class="nav-number">8.1.</span> <span class="nav-text">适配器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">9.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/09/05/wheel/cicada2/';
      var disqus_title = "「造个轮子」——cicada 源码分析";
      var disqus_url = 'http://crossoverjie.top/2018/09/05/wheel/cicada2/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
